package com.example.administrator.printoutindemo;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.dds.soap.SoapListener;
import com.dds.soap.SoapParams;
import com.dds.soap.SoapUtil;
import com.example.administrator.printoutindemo.adapter.CangkuAdapter;
import com.example.administrator.printoutindemo.adapter.GridImageAdapter;
import com.example.administrator.printoutindemo.base.BaseActivity;
import com.example.administrator.printoutindemo.bean.CangKuBean;
import com.example.administrator.printoutindemo.http.SPUtil;
import com.example.administrator.printoutindemo.view.FullyGridLayoutManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hss01248.frescopicker.FrescoIniter;
import com.hss01248.photoouter.PhotoCallback;
import com.hss01248.photoouter.PhotoUtil;
import com.jess.arms.base.BaseConstants;
import com.jess.arms.utils.ArmsUtils;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.xiaoxing.gifloadingview.LoadingDialogUtil;

import org.kobjects.base64.Base64;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.iwf.photopicker.utils.ProxyTools;
import me.jessyan.armscomponent.commonres.utils.BottomDialogUtil;
import me.jessyan.armscomponent.commonres.utils.ToolbarUtils;
import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by Administrator on 2018/9/11.
 */

public class CangKuActivity extends BaseActivity {

    View mEmptyLayout;
    TextView empty_text;
    ImageView empty_image;
    private EditText et_weizhi;
    private ListView lv_ck;
    private List<CangKuBean> mlist = new ArrayList<>();
    private CangkuAdapter mAdapter;
    private TextView tv_dayin, tv_xmmc, tv_gys, tv_ddh, tv_wlmc;
    private EditText tv_shuliang;
    private ImageView tv_check, iv_img, iv_backc, tv_pai;
    private Bitmap bitmap = null;
    private String xiangMuMingCheng, gongYingShang, dingDanHao, wuLiaoMingCheng, shuLiang;
    private BottomDialogUtil mBottomDialogUtilShare;

    private int maxSelectNum = 10;//最多到几张还可以选择
    private List<LocalMedia> selectList = new ArrayList<>();
    private GridImageAdapter adapter;
    private RecyclerView mRecyclerView;
    private PopupWindow pop;
    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {

        @Override
        public void onAddPicClick() {
            showPop();
        }
    };
    private String mIsqualityplan = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cangku);
        ToolbarUtils.initToolbarTitleBack(this, getString(R.string.cang_wei));
        PhotoUtil.init(this, new FrescoIniter());

        initEmpty();

        iv_backc = (ImageView) findViewById(R.id.iv_backc);

        tv_xmmc = (TextView) findViewById(R.id.tv_xmmc);
        tv_gys = (TextView) findViewById(R.id.tv_gys);
        tv_ddh = (TextView) findViewById(R.id.tv_ddh);
        tv_wlmc = (TextView) findViewById(R.id.tv_wlmc);
        tv_shuliang = (EditText) findViewById(R.id.tv_shuliang);

        et_weizhi = (EditText) findViewById(R.id.et_weizhi);
        tv_check = (ImageView) findViewById(R.id.tv_check);
        tv_pai = (ImageView) findViewById(R.id.tv_pai);
        iv_img = (ImageView) findViewById(R.id.iv_img);
        lv_ck = (ListView) findViewById(R.id.lv_ck);

        getBundleValue();


        mAdapter = new CangkuAdapter(CangKuActivity.this, mlist, this);
        lv_ck.setAdapter(mAdapter);
        iv_backc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_pai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// 调用相机
//                startActivityForResult(in, 2);
                xiuGaiTouXiang();
            }
        });

        tv_check.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getUserSpaceList();
                if (bitmap != null) {
                    SPUtil.putString(CangKuActivity.this, "tag", "a");
                }
            }
        });

        String bt = SPUtil.getString(this, "zhaopian", "");

        if (!TextUtils.isEmpty(bt)) {
            tv_pai.setImageBitmap(getHistoryPicture(bt));
        }
//        iv_img.setImageBitmap(getHistoryPicture());


        tv_shuliang.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String etNum = tv_shuliang.getText().toString();
                if (!TextUtils.isEmpty(etNum) && Double.parseDouble(etNum) > 0) {
                    if (Double.parseDouble(etNum) > Double.parseDouble(shuLiang)) {
                        tv_shuliang.setText(shuLiang + "");
                        SPUtil.putString(CangKuActivity.this, "shuliang", shuLiang);
                        ArmsUtils.makeText(CangKuActivity.this, "数量不能大于" + shuLiang);
                        return;
                    }
                }
                SPUtil.putString(CangKuActivity.this, "shuliang", tv_shuliang.getText().toString());

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });


        mRecyclerView = findViewById(R.id.recycler);
        initWidget();
        initImgs();

    }

    private void initEmpty() {
        mEmptyLayout = (View) findViewById(R.id.empty);
        empty_text = (TextView) findViewById(R.id.empty_text);
        empty_image = (ImageView) findViewById(R.id.empty_image);

        empty_image.setImageResource(com.xiaoxing.zhinenghuacangku.R.drawable.ic_empty);
        empty_text.setTextColor(Color.parseColor("#CFCFCF"));
        empty_text.setText("暂无数据");
    }

    private void getBundleValue() {

        if (getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();

            xiangMuMingCheng = bundle.getString("xiangMuMingCheng");
            gongYingShang = bundle.getString("gongYingShang");
            dingDanHao = bundle.getString("dingDanHao");
            wuLiaoMingCheng = bundle.getString("wuLiaoMingCheng");
            shuLiang = bundle.getString("shuliang");
            mIsqualityplan = bundle.getString("isqualityplan");

            tv_xmmc.setText(xiangMuMingCheng);
            tv_gys.setText(gongYingShang);
            tv_ddh.setText(dingDanHao);
            tv_wlmc.setText(wuLiaoMingCheng);
            tv_shuliang.setText(shuLiang);
        }
    }

    private void xiuGaiTouXiang() {
        LinearLayout root = (LinearLayout) LayoutInflater.from(this).inflate(com.xiaoxing.zhinenghuacangku.R.layout.sales_client_bottom_dialog_pai_zhao, null);
        Button btn_xiang_ce = root.findViewById(me.iwf.photopicker.R.id.btn_xiang_ce);
        Button ben_xiang_ji = root.findViewById(me.iwf.photopicker.R.id.ben_xiang_ji);
        Button btn_qu_xiao = root.findViewById(me.iwf.photopicker.R.id.btn_qu_xiao);
        btn_qu_xiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
            }
        });
        btn_xiang_ce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();

                PhotoUtil.begin()
                        .setNeedCropWhenOne(false)
                        .setNeedCompress(false)
                        .setMaxSelectCount(1)

                        .start(CangKuActivity.this, 33, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
//
                                try {
                                    createMaterialForInstoreAuto(compressedPath);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
//                                refresh1(originalPaths);

                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });
        ben_xiang_ji.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBottomDialogUtilShare != null)
                    mBottomDialogUtilShare.dismissDiaolog();
                PhotoUtil.statusBarColor = com.xiaoxing.zhinenghuacangku.R.color.public_black;
                PhotoUtil.titleBarColor = com.xiaoxing.zhinenghuacangku.R.color.public_black;
                PhotoUtil.cropAvatar(true).setCropMuskOvalFalse()
                        .start(CangKuActivity.this, 23, ProxyTools.getShowMethodInfoProxy(new PhotoCallback() {
                            @Override
                            public void onFail(String msg, Throwable r, int requestCode) {
                            }

                            @Override
                            public void onSuccessSingle(String originalPath, String compressedPath, int requestCode) {
                                try {
                                    createMaterialForInstoreAuto(compressedPath);
                                } catch (Exception e) {
                                    e.printStackTrace();

                                }
                            }

                            @Override
                            public void onSuccessMulti(List<String> originalPaths, List<String> compressedPaths, int requestCode) {
                            }

                            @Override
                            public void onCancel(int requestCode) {
                            }
                        }));
            }
        });

        mBottomDialogUtilShare = new BottomDialogUtil(CangKuActivity.this, root);
        mBottomDialogUtilShare.showDiaolog();

    }

    /**
     * @param
     * @return
     * @method
     * @description 获取仓位 统一调用  方法 GetUserSpaceList 改为 GetUserSpaceListQ
     *
     * 质检的不用了，还用之前的方法 GetUserSpaceList
     * <p>
     * 说明：
     * GetUserSpaceListQ(string user_id, string spname,int isquality=0)
     * isquality从上面返回的isqualityplan中获取
     * <p>
     * 用法同GetUserSpaceList
     * <p>
     * 创建一批 sptname='入库待检区' 的一把仓位
     * @date: 2020/8/14  9:11
     * @author: 小星
     */
    private void getUserSpaceList() {

        LoadingDialogUtil.showGifdialog2(getSupportFragmentManager(), R.drawable.public_loading);

        String methodName = "GetUserSpaceList";

        lv_ck.setVisibility(View.GONE);
        mEmptyLayout.setVisibility(View.VISIBLE);

        SoapParams params = new SoapParams();
        params.put("user_id", SPUtil.getString(CangKuActivity.this, "iduser", ""));
        params.put("spname", et_weizhi.getText().toString());
        params.put("isquality", mIsqualityplan); //0 表示无质检计划 1表示有质检计划

        /**
         * 请求
         */
        SoapUtil.getInstance(getContext()).callEntry(getUrl(), BaseConstants.NAME_SPACE, methodName, params, new SoapListener() {
            @Override
            public void onSuccess(int statusCode, SoapObject object) {
                LoadingDialogUtil.dismissDialog();

                String result = object.getProperty(methodName + "Result").toString();
                if (result != null && !result.equals("[]") && !result.equals("anyType{}") && !result.equals("Error") && !result.equals("-100")) {
                    mAdapter.shua();
                    List<CangKuBean> cangKuBeen = new Gson().fromJson(result, new TypeToken<List<CangKuBean>>() {
                    }.getType());
                    if (cangKuBeen != null && cangKuBeen.size() > 0) {
                        mEmptyLayout.setVisibility(View.GONE);
                        lv_ck.setVisibility(View.VISIBLE);
                        mAdapter.addAll(cangKuBeen);

                    } else {
                        mEmptyLayout.setVisibility(View.VISIBLE);
                        lv_ck.setVisibility(View.GONE);

                    }
                } else {

                }

            }

            @Override
            public void onFailure(int statusCode, String content, Throwable error) {
                LoadingDialogUtil.dismissDialog();
                ArmsUtils.makeText(getContext(), error.getMessage());

            }

            @Override
            public void onFailure(int statusCode, SoapFault fault) {
                LoadingDialogUtil.dismissDialog();

            }
        }, getAapiUserName(), getApiPwd());

    }

    /**
     * 获取保存的历史拍照
     *
     * @return
     */
    private Bitmap getHistoryPicture(String bt) {
        ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(bt));
//            Drawable drawable = Drawable.createFromStream(bis, "");
        Bitmap bitmap1 = BitmapFactory.decodeStream(bis);
        return bitmap1;
    }

    private void initWidget() {
        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(manager);
        adapter = new GridImageAdapter(this, onAddPicClickListener);
        adapter.setList(selectList);
        adapter.setSelectMax(maxSelectNum);
        mRecyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new GridImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, View v) {
                if (selectList.size() > 0) {
                    LocalMedia media = selectList.get(position);
                    String pictureType = media.getPictureType();
                    int mediaType = PictureMimeType.pictureToVideo(pictureType);
                    switch (mediaType) {
                        case 1:
                            // 预览图片 可自定长按保存路径
                            //PictureSelector.create(MainActivity.this).externalPicturePreview(position, "../.../", selectList);
                            PictureSelector.create(CangKuActivity.this).externalPicturePreview(position, selectList);
                            break;
                        case 2:
                            // 预览视频
                            PictureSelector.create(CangKuActivity.this).externalPictureVideo(media.getPath());
                            break;
                        case 3:
                            // 预览音频
                            PictureSelector.create(CangKuActivity.this).externalPictureAudio(media.getPath());
                            break;
                    }
                }
            }
        });
    }

    private void initImgs() {
        List<LocalMedia> images = new ArrayList<>();


        String bt_path1 = SPUtil.getString(this, "zhaopian_path1", "");
        String bt_path2 = SPUtil.getString(this, "zhaopian_path2", "");
        String bt_path3 = SPUtil.getString(this, "zhaopian_path3", "");
        String bt_path4 = SPUtil.getString(this, "zhaopian_path4", "");
        String bt_path5 = SPUtil.getString(this, "zhaopian_path5", "");
        String bt_path6 = SPUtil.getString(this, "zhaopian_path6", "");
        String bt_path7 = SPUtil.getString(this, "zhaopian_path7", "");
        String bt_path8 = SPUtil.getString(this, "zhaopian_path8", "");
        String bt_path9 = SPUtil.getString(this, "zhaopian_path9", "");
        String bt_path10 = SPUtil.getString(this, "zhaopian_path10", "");

        if (!TextUtils.isEmpty(bt_path1)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path1);
            localMedia.setPosition(1);
            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path2)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path2);
            localMedia.setPosition(2);
            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path3)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path3);
            localMedia.setPosition(3);

            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path4)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path4);
            localMedia.setPosition(4);

            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path5)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path5);
            localMedia.setPosition(5);

            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path6)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path6);
            localMedia.setPosition(6);

            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path7)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path7);
            localMedia.setPosition(7);

            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path8)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path8);
            localMedia.setPosition(8);

            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path9)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path9);
            localMedia.setPosition(9);

            images.add(localMedia);
        }
        if (!TextUtils.isEmpty(bt_path10)) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(bt_path10);
            localMedia.setPosition(10);

            images.add(localMedia);
        }


        selectList.addAll(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
        // LocalMedia 里面返回三种path
        // 1.media.getPath(); 为原图path
        // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
        // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
        // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
        adapter.setList(selectList);
        adapter.notifyDataSetChanged();
    }

    private void createMaterialForInstoreAuto(String compressedPath) throws Exception {
        String imgStr = ArmsUtils.bitmapToString(compressedPath);
        SPUtil.putString(CangKuActivity.this, "zhaopian", imgStr);
        Bitmap bitmap = BitmapFactory.decodeFile(compressedPath);
        iv_img.setImageBitmap(bitmap);
        tv_pai.setImageBitmap(bitmap);
    }

    private void showPop() {
        View bottomView = View.inflate(CangKuActivity.this, R.layout.layout_bottom_dialog, null);
        TextView mAlbum = bottomView.findViewById(R.id.tv_album);
        TextView mCamera = bottomView.findViewById(R.id.tv_camera);
        TextView mCancel = bottomView.findViewById(R.id.tv_cancel);

        pop = new PopupWindow(bottomView, -1, -2);
        pop.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        pop.setOutsideTouchable(true);
        pop.setFocusable(true);
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        pop.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        pop.setAnimationStyle(R.style.main_menu_photo_anim);
        pop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);

        View.OnClickListener clickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (view.getId()) {
                    case R.id.tv_album:
                        //相册
                        try {
                            PictureSelector.create(CangKuActivity.this)
                                    .openGallery(PictureMimeType.ofImage())
                                    .maxSelectNum(maxSelectNum)
                                    .minSelectNum(1).enableCrop(true)
                                    .cropWH(300, 300)
                                    .imageSpanCount(4)
                                    .selectionMode(PictureConfig.MULTIPLE)
                                    .forResult(PictureConfig.CHOOSE_REQUEST);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        break;
                    case R.id.tv_camera:
                        //拍照
                        PictureSelector.create(CangKuActivity.this)
                                .openCamera(PictureMimeType.ofImage()).enableCrop(true)
                                .cropWH(300, 300)
                                .forResult(PictureConfig.CHOOSE_REQUEST);
                        break;
                    case R.id.tv_cancel:
                        //取消
                        //closePopupWindow();
                        break;
                }
                closePopupWindow();
            }
        };

        mAlbum.setOnClickListener(clickListener);
        mCamera.setOnClickListener(clickListener);
        mCancel.setOnClickListener(clickListener);
    }

    public void closePopupWindow() {
        if (pop != null && pop.isShowing()) {
            pop.dismiss();
            pop = null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> images;
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调

                    images = PictureSelector.obtainMultipleResult(data);
                    selectList.addAll(images);

//                    selectList = PictureSelector.obtainMultipleResult(data);
                    // LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    adapter.setList(selectList);
                    adapter.notifyDataSetChanged();


                    try {
                        for (int i = 0; i < selectList.size(); i++) {
                            String imgStr = ArmsUtils.bitmapToString(selectList.get(i).getPath());
                            SPUtil.putString(CangKuActivity.this, "zhaopian" + (i + 1), imgStr);
                            SPUtil.putString(CangKuActivity.this, "zhaopian_path" + (i + 1), selectList.get(i).getPath());

                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
//        else {
////            if (resultCode != 0)
//            PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
////        }
//        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
        if (requestCode == 103) {
            xiuGaiTouXiang();
        }
    }

//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//
////        if (resultCode == Activity.RESULT_OK) {
////            Bundle bundle = data.getExtras();
////            bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据，并转换为Bitmap图片格式
////            if (null != bitmap) {
////                ByteArrayOutputStream os = new ByteArrayOutputStream();
////                bitmap.compress(Bitmap.CompressFormat.PNG, 100, os);
////                byte[] photo = os.toByteArray();
////                String img = new String(Base64.encode(photo));
////                SPUtil.putString(CangKuActivity.this, "zhaopian", img);
////            }
////
////            iv_img.setImageBitmap(bitmap);
////            tv_pai.setImageBitmap(bitmap);
//////            iv_img.setImageBitmap(getHistoryPicture());
////
////        }else {
////            if (resultCode != 0)
//        PhotoUtil.onActivityResult(this, requestCode, resultCode, data);
////        }
//    }

    /**
     * 清空图片缓存，包括裁剪、压缩后的图片，避免OOM
     * 注意:必须要在上传完成后调用 必须要获取权限
     */
    private void clearCache() {
        RxPermissions permissions = new RxPermissions(this);
        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE).subscribe(new Observer<Boolean>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(Boolean aBoolean) {
                if (aBoolean) {
                    //清除缓存
                    PictureFileUtils.deleteCacheDirFile(CangKuActivity.this);
                } else {
                    Toast.makeText(CangKuActivity.this, getString(R.string.picture_jurisdiction), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onComplete() {
            }
        });
    }

}
